$(document).ready(function(){

    var userName = window.localStorage.getItem("fiuserName");
    $(".fiUsername").html(userName);
    $.ajax({
        type : "POST",
        url:"http://59.110.114.107:8888/bank/getBankInformation/",
        data:{
            userName :userName
        },
        success:function(result){
            if(!window.localStorage){
                console.log("浏览器不支持localstorage");
            }else{
                var bkName = result.data.bankName;
                window.localStorage.setItem("bankName", bkName);
                window.localStorage.setItem("bankId", result.data.bankId);

            }
            $("#bankName").text(result.data.bankName);
            $("#bankNum").text(result.data.bankId);
        },
        error:function(){
            alert("错误");
        }
    });

    var bankName = window.localStorage.getItem("bankName");

    //-----------------产品发布--------------------------------
    $("#release").click(function(){
        // var generality =$("#general_product").val().substr(0,1);
        // var guaranteeMode = $("#guarantee_mode").val().substr(0,1);
        // var institutionType = $("#organizationType").val().substr(0,1);
        // var internetLoanType = $("#internetLoanType").val().substr(0,1);
        // var loanLimit = $("#loan_limit").val().substr(0,1);
        // var loanType = $("#loan_category").val().substr(0,1);
        // var paymentType = $("#pay").val().substr(0,1);
        // var productProperties = $("#policy_product").val().substr(0,1);


        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/productRelease",
            data:{
                bankName:$('#bankName').text(),
                description:$("#description").val(),
                fkBankId:$("#bankNum").text(),
                generality:$("#general_product option:selected").val(),
                guaranteeMode:$("#guarantee_mode option:selected").val(),
                institutionType:$("#organizationType option:selected").val(),
                internetLoanType:$("#internetLoanType option:selected").val(),
                loanLimit:$("#loan_limit option:selected").val(),
                loanPeriod:$("#loan_period").val(),
                loanType:$("#loan_category option:selected").val(),
                paymentType:$("#pay option:selected").val(),
                productName:$("#ProductName").val(),
                productProperties:$("#policy_product option:selected").val(),
                rateLowerLimit:$("#rateLowerLimit").val(),
                rateUpperLimit:$("#rateUpperLimit").val(),
                useArea:$("#use_area").val()
            },
            success:function(result){
                alert(result.meta.message);
                var form = $(".form-horizontal");
                $(form)[0].reset();
            },
            error:function(){
                alert("错误");
            }
        });
    });

    //-----------------企业申请--------------------------------
    var productArray = new Array();
    $("#productApply").click(function(){
        var bankName = window.localStorage.getItem("bankName");
        // bankName=$('.fiUsername').text();
        console.log(bankName)
        //alert(bankName);
        $(".products-list").html("");
        $(".btn-muted").eq(0).siblings().removeClass("current");
        $(".btn-muted").eq(0).addClass("current");
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/productApply",
            data:{
                bankName:bankName
            },
            // 请求发送之前（发送请求前可修改XMLHttpRequest对象的函数，如添加自定义HTTP头。）。
            // beforeSend:function(XMLHttpRequest){
            //     $("#loading").html("<img src='https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%8A%A0%E8%BD%BD%E4%B8%AD&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=1992466295,1145446755&os=4150192825,3836185010&simid=0,0&pn=0&rn=1&di=8250&ln=626&fr=&fmq=1560692862295_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&hs=2&objurl=http%3A%2F%2Fphotocdn.sohu.com%2F20160127%2Fmp56791937_1453886827459_16.gif&rpstart=0&rpnum=0&adpicid=0&force=undefined' />");
            // },
            success:function(result){
                if(result.data == null){
                    alert("无结果！")
                }else{
                    // $("#loading").empty();
                    for(var i= 0;i<result.data.length;i++){
                        var ProductName = result.data[i].fkProductName;
                        if($.inArray(ProductName,productArray) < 0){
                            productArray.push(ProductName);
                             $("#productNameSelect").append('<a class="productSelect btn-muted" >'+ProductName+'</a>');
                        }
                        var comment=result.data[i].comment==null?"":result.data[i].comment;
                        var productsItem = '<dl class="products-item"><dt><img src="images/1boc.png"></dt><dd>'+
                            '<div class="products-title">'
                                +'<span class="products-type_item"><span class="enterpriseNameSpan">'+result.data[i].enterpriseName+'</span></span>'
                                +'<span class="products-type_item"><span>社会统一信用代码：</span><em>'+result.data[i].fkSocialCode+'</em></span>'
                            +'</div>'+
                            '<div class="products-info"><div class="products-type">'+
                            '<span class="products-type_item"><span>金融产品名称：</span><em class="fkProductName">'+result.data[i].fkProductName
                            +'</em></span><span class="products-type_item"><span>申请时间：</span><em>'
                            +result.data[i].requestTime.substr(0,10)
                            +'</em></span>'
                            +'</div>'+'' +
                            '</div><div class="products-action">'+
                                '<span class="products-type_item"><span>申请进度：</span><input placeholder="'+comment+'"></span>'+
                                '<button type="button" class="comment btn btn-default" >修改进度</button>'+'' +
                                '<button type="button" class="products-btn btn btn-default">详情</button>'+'' +
                                '<button type="button" class="agree-btn btn btn-default" id="'+result.data[i].requestId+'">同意</button>' +
                                '<button type="button" class="refuse-btn btn btn-default">拒绝</button>'
                            +'</div></dd></dl>';

                        $(".products-list").append(productsItem);

                    }

                }

            },
            // 请求完成后的回调函数 (请求成功或失败之后均调用)
            complete:function(XMLHttpRequest,textStatus){
                $("#loading").empty();
            },
            // 请求失败时调用此函数。
            error:function(XMLHttpRequest,textStatus,errorThrown){
                $("#loading").empty();
                alert("错误");
            }
        });
    });


    //修改进度
    $(".products-list").on("click",".comment",function(){
        var comment=$(this).prev().children("input").val();
        var request_id=$(this).next().next()[0].id;
        if(comment==""){
            alert("没有输入修改的进度情况");
        }else{

            $.ajax({
                type : "POST",
                url:"http://59.110.114.107:8888/bank/modifyApplySchedule",
                data:{
                    request_id:request_id,
                    Comment:comment
                },
                success:function(result){
                    if(result.meta.success ){
                        alert(result.meta.message);
                    }else{
                        alert(result.meta.message);
                        //$("#deResult").css("display", "block");
                    }
                },
                error:function(){
                    alert("错误");
                }
            });
        }


    })
    //根据产品名检索
    $("#productNameSelect").on("click",".productSelect",function(){
        // for(var j=0;j<$(".btn-muted").length;j++){
        //     // alert($(".btn-muted").eq(i).html());
        //     $(".btn-muted").eq(i).removeClass("current");
        // }
        $(this).siblings().removeClass("current");
        $(this).addClass("current");
        var productName =  $(this).text();
        for(var i=0;i<$(".fkProductName").length;i++){
            $(".fkProductName").eq(i).parents(".products-item").css("display","block");
            var fkProductName = $(".fkProductName").eq(i).text();
            if(productName != fkProductName){
                $(".fkProductName").eq(i).parents(".products-item").css("display","none");
            }

        }
    });

    //产品名不限时
    $("#productNameSelect").on("click",".productUnlimited",function(){
        // for(var j=0;j<$(".btn-muted").length;j++){
        //     $(".btn-muted").eq(i).removeClass("current");
        // }
        $(this).siblings().removeClass("current");
        $(this).addClass("current");

        for(var i=0;i<$(".fkProductName").length;i++){
            $(".fkProductName").eq(i).parents(".products-item").css("display","block");
        }


    });

    //----------------------企业详情----------------------------
    $(".products-list").on("click",".products-btn",function(){
        $(".enterpriseApp").css("display","none");
        $("#companyDetail").css("display","block");
        var enterpriseName =  $(this).parents('dd').children('.products-title').children('.products-type_item').children('.enterpriseNameSpan').text();
        //alert(enterpriseName);
        //window.localStorage.setItem("enterpriseName", enterpriseName);
        //window.location.href = "companyDetail.html";
        console.log(enterpriseName)
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/enterprieseInfoCkeck",
            data:{
                enterpriseName:enterpriseName
            },
            success:function(result){
                //alert(result.meta.message)
                var regionArr = ["碑林区","莲湖区","灞桥区","雁塔区","阎良区","未央区","新城区","长安区","临潼区"];
                var creditRate=['','A','AA','AAA','AAAA','AAAAA']
                var region = regionArr[result.data.region];
                $("#enterpriseName").text(result.data.enterpriseName) ;
                $("#socialCode").text(result.data.socialCode) ;
                $("#ownerName").text(result.data.ownerName) ;
                $("#region").text(region) ;
                $("#street").text(result.data.street) ;
                $("#ownerPhone").text(result.data.ownerPhone) ;
                $("#contactName").text(result.data.contactName) ;
                $("#contactPhone").text(result.data.contactPhone) ;
                $("#businessScop").text(result.data.businessScop) ;
                $("#creditRate").text(creditRate[parseInt(result.data.creditRate)]);
                showMap(result.data.establishAddress,result.data.longAndLat);
            },
            error:function(){
                alert("错误");
            }
        });
    });
    $(".return_btn").click(function(){
        // $(".products-list").on("click",".products-btn",function(){
        $(".enterpriseApp").css("display","block");
        $("#companyDetail").css("display","none");
    }) ;

    //---------------申请同意
    $(".products-list").on("click",".agree-btn",function(e){
        console.log(e)
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/productDeal",
            data:{
                request_id:e.target.id
            },
            success:function(result){
                if(result.meta.success ){
                    alert(result.meta.message);
                }else{
                    alert(result.meta.message);
                    //$("#deResult").css("display", "block");
                }
            },
            error:function(){
                alert("错误");
            }
        });
    });

//---------------申请拒绝
    $(".products-list").on("click",".refuse-btn",function(){
        var request_id=$(this).prev()[0].id;
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/productApplyRefuse",
            data:{
                request_id:request_id
            },
            success:function(result){
                if(result.meta.success ){
                    alert(result.meta.message);
                }else{
                    alert(result.meta.message);
                    //$("#deResult").css("display", "block");
                }
            },
            error:function(){
                alert("错误");
            }
        });
    });
    // ---------------企业需求----------------------

    $("#demandCheck").click(function(){
        $("#tbody").html("");
        var guaranteeMode=$("#danbao option:selected").val();
        var loanLimit=$("#loanLimit option:selected").val();
        var loanPeriod=$("#loanTime").val();
        var lowerLimit=$("#rate_lower_limmit").val();
        var upperLimit=$("#rate_upper_limmit").val();
        var data={};
        var Limit=['100万及以下','200万及以下','300万及以下','500万及以下','1000万及以下','1000万以上']
        guaranteeMode?data.guaranteeMode=guaranteeMode:null;
        loanLimit?data.loanLimit=loanLimit:null;
        loanPeriod?data.loanPeriod=loanPeriod:null;
        lowerLimit?data.lowerLimit=lowerLimit:null;
        upperLimit?data.upperLimit=upperLimit:null;
        console.log(data);
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/demandCheck",
            data:data,
            success:function(result){

                if(result.meta.success ){
                    if(result.data.length == 0){
                        alert("无符合条件信息！");
                    }else{
                        $("#deResult").css("display", "none");
                        // $("#enterpriseNeed-table").remove("#deResult");
                        for(var i= 0;i<result.data.length;i++){
                            debugger
                            var demandCheck = '<tr><td>'+result.data[i].fkSocialCode
                                +'</td><td>'+result.data[i].enterpriseName
                                +'</td><td>'+Limit[result.data[i].loanLimit]
                                +'</td><td>'+result.data[i].rateLowerLimit
                                +'</td><td>'+result.data[i].rateUpperLimit
                                +'</td><td>'+result.data[i].loanPeriod
                                +'</td><td>'+result.data[i].guaranteeMode
                                +'</td><td>'+result.data[i].financingPurposes
                                +'</td><td>'+result.data[i].projectSituation
                                +'</td><td>'+result.data[i].remark
                                +'</td><td><button class="btn btn-default" style="background-color:#8a6d3b " onclick="sendMsg(\''+result.data[i].fkSocialCode+'\')">发送短信</button></td></tr>';

                            $("#tbody").append(demandCheck);
                        }
                    }

                }else{
                    alert(result.meta.message);
                    //$("#deResult").css("display", "block");
                }
            },
            error:function(){
                alert("错误");
            }
        });
    });
    $(".myTabContent-title a").click(function () {
        sessionStorage.setItem("isLogin","true");
        window.location.href="index.html";
    })






    //------------我的产品
    $("#product-tab").click(function () {
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/getProductByBankId",
            data:{
                pageNum:1,
                pageSize:10000,
                fkBankId:window.localStorage.getItem("bankId")

            },
            success:function(result){

                if(result.meta.success ){
                    if(result.data.length == 0){
                        alert("无符合条件信息！");
                    }else{
                        // $("#deResult").css("display", "none");
                        // $("#enterpriseNeed-table").remove("#deResult");
                        var data=result.data["bankProduct List"];
                        var Limit=['100万及以下','200万及以下','300万及以下','500万及以下','1000万及以下','1000万以上'];
                        var guaranteeMode=['抵押','信保基金','一般保证','信用','实际控制人夫妇提供个人连带担保'];
                        var yesNo=['否','是'];
                        console.log(data);
                        var d=data.map(function (item,index) {
                            return '<dl class="products-item"><dt><img src="images/'+item.bankName+'.png"></dt><dd>'+
                                '<div class="products-title">'
                                +'<span class="products-type_item"><span class="enterpriseNameSpan">产品名称：<em>'+item.productName+'</em></span></span>'
                                +'<span class="products-type_item"><span>发布机构：</span><em>'+item.bankName+'</em></span>'
                                +'</div>'+
                                '<div class="products-info"><div class="products-type">'+
                                '<span class="products-type_item"><span>参考利率范围：</span><em class="fkProductName">'+item.rateLowerLimit+'-'+item.rateUpperLimit
                                +'</em></span><span class="products-type_item"><span>是否网贷直联：</span><em>'
                                +yesNo[item.internetLoanType]
                                +'</em></span><span class="products-type_item"><span>是否通用产品：</span><em class="fkProductName">'+yesNo[item.generality]+
                                '</em></span><span class="products-type_item"><span>是否人民币：</span><em class="fkProductName">'+yesNo[item.paymentType]+
                            '</em></span><span class="products-type_item"><span>贷款类别：</span><em class="fkProductName">'+item.loanType+
                            '</em></span><span class="products-type_item"><span>贷款额度：</span><em class="fkProductName">'+Limit[item.loanLimit]+
                            '</em></span><span class="products-type_item"><span>贷款期限：</span><em class="fkProductName">'+item.loanPeriod+
                            '月</em></span><span class="products-type_item"><span>担保方式：</span><em class="fkProductName">'+guaranteeMode[item.guaranteeMode]+
                                '</em></span><span class="products-type_item"><span>适用设区市：</span><em class="fkProductName">'+item.useArea+
                                '</em></span>'
                                +'</div></dd></dl>';
                        })
                        $(".myProduct-list").append(d);
                    }

                }else{
                    alert(result.meta.message);
                    //$("#deResult").css("display", "block");
                }
            },
            error:function(){
                alert("错误");
            }
        });
    })
    //---------------------退出

    $("#business_tab").click(function () {
        var list=$("#business_show span");
        $.ajax({
            type:"POST",
            url:"http://59.110.114.107:8888/bank/getBankStatics",
            data:{
                bankName:window.localStorage.getItem("bankName")
            },
            success:function (result) {
                if(result.meta.success&&result.data!=null){
                    list.eq(0).text(result.data.bankProductCount);
                    list.eq(1).text(result.data.productAmountCount);
                    list.eq(2).text(result.data.bankProductApplyCount);
                    list.eq(3).text(result.data.dealCount);
                    list.eq(4).text(result.data.dealAmountCount);
                    list.eq(5).text(result.data.applyButNotDealCount);
                    list.eq(6).text(result.data.applyButNotDealAmountCount);
                    list.eq(7).text(result.data.refuseCount);
                    list.eq(8).text(result.data.refuseAmountCount);

                }else{
                    alert(result.meta.message);
                }

            },
            error:function (err) {
                console.log(err);
            }
        })

    });

    $("#detail_tab").click(function(){
        $("#detail_tbody").html("");
        var Limit=['100万及以下','200万及以下','300万及以下','500万及以下','1000万及以下','1000万以上'];
        var Status=["申请中","已成功","已拒绝"];
        $.ajax({
            type : "POST",
            url:"http://59.110.114.107:8888/bank/getProductApplyInfo",
            data:{
                bankName:window.localStorage.getItem("bankName")
            },
            success:function(result){
                if(result.meta.success ){
                    if(result.data.productApplyInfoList.length == 0){
                        alert("无符合条件信息！");
                    }else{
                        //console.log(result.data);
                        $("#detail_deResult").css("display", "none");
                        for(var i= 0;i<result.data.productApplyInfoList.length;i++){
                            var item=result.data.productApplyInfoList[i];
                            var fundUsage=item.fundUsage==null?"":item.fundUsage;
                            var time=item.requestTime.substr(0,16).replace('T'," ")
                            var demandCheck = '<tr><td>'+item.fkProductName
                                +'</td><td>'+item.enterpriseName
                                +'</td><td>'+item.fkSocialCode
                                +'</td><td>'+Limit[item.loanLimit]
                                +'</td><td>'+item.rateLowerLimit
                                +'</td><td>'+item.rateUpperLimit
                                +'</td><td>'+item.loanPeriod
                                +'</td><td>'+fundUsage
                                +'</td><td>'+item.comment
                                +'</td><td>'+Status[item.status]
                                +'</td><td>'+time
                                +'</td></tr>';
                            $("#detail_tbody").append(demandCheck);
                        }
                    }

                }else{
                    alert(result.meta.message);
                    //$("#deResult").css("display", "block");
                }
            },
            error:function(){
                alert("错误");
            }
        });
    });


        //---------------------退出
    $(".exit").click(function(){
        alert("退出登录！");
        window.localStorage.clear();
        window.sessionStorage.setItem("isLogin","false");
        localStorage.setItem("isLogin","false");
        window.location.href = "index.html";
    });


});

//========baidu ditu ==============
function showMap(address,longAndLat) {
    $('#allmap').show();
    debugger
    var map = new BMap.Map("allmap");
    var lon="";
    var lat ="";
    if(longAndLat != null && longAndLat !='' && longAndLat !=undefined){
        var longlat = longAndLat.split(",")
        lon = longlat[0];
        lat = longlat[1];
    }
    var point = new BMap.Point(lon,lat);

    var pointCenter = new BMap.Point(108.81994,34.292765);
    map.centerAndZoom(pointCenter, 12);
    var marker = new BMap.Marker(point);  // 创建标注
    map.addOverlay(marker);              // 将标注添加到地图中

    var label = new BMap.Label(address,{offset:new BMap.Size(20,-10)});
    label.setStyle({
        color : "red",
        maxWidth:"none",   //去除bootstrap中样式
        fontSize : "12px",
        height : "20px",
        lineHeight : "20px",
        fontFamily:"微软雅黑"
    });
    marker.setLabel(label);
}
function sendMsg(socialCode){
    debugger
    $.ajax({
        type: "POST",
        url: "http://59.110.114.107:8888/bank/demandCheckSendMessage",
        data: {
            socialCode: socialCode
        },
        success: function (result) {

            alert(result.meta.message);

        }
    });
}

